import type { SerialTaskExecuteContext } from '../handler'
import type { PrivateCustomEventName } from '../types'

import { SerialHandler } from '../handler'
import TextStreamSlicer from '../text-stream-slicer/index'
import { createEventBus } from '../utils'

const $bus = createEventBus<PrivateCustomEventName>()

class TextSplit extends SerialHandler<string, string> {
  private textStreamSlicer = new TextStreamSlicer()

  public execute(
    context: SerialTaskExecuteContext<string, string>,
  ): void {
    if (context.isLastExecute) {
      this.textStreamSlicer.processText('', true).forEach((paragraph) => {
        this.forwardToHandler(paragraph)
      })
    }
    else {
      this.textStreamSlicer.processText(context.taskItem.original!).forEach((paragraph) => {
        this.forwardToHandler(paragraph)
      })
    }
    this.taskCompletedCallback()
  }

  protected onFinish(): void {
    $bus.emit('_textSplitFinish')
  }
}

export default TextSplit
